<template>
    <div>
      <van-nav-bar title="兑换" left-arrow @click-left="onBack" />
      <div v-if="this.show===2">
        <h3>请先登录</h3>
        <van-button type="primary" round @click="goToLogin">
          登录
        </van-button>
      </div>
      <div v-if="this.show===1">
        <h4>
          可用汪汪粮：{{user.userglod2}}
        </h4>
        <div>
          <van-cell-group>
            <van-field v-model="exchange.number" label="兑换数量" placeholder="请输入兑换数量" />
          </van-cell-group>
          <van-button type="info" round @click="toExchangeGlod()" style="margin-top: 50px">
            确认兑换
          </van-button>
        </div>
      </div>

    </div>
</template>

<script>
import axios from "axios";
  export default {
    data(){
      return{
        exchange:{},
        one:{},
        user:{},
        show:'',
      }
    },
    methods:{
      goToLogin(){
        this.$router.push("/login")
      },
      toExchangeGlod(){
          if (this.exchange.number==null){
            this.$toast.fail('请输入兑换数量');
          }else{
            if (this.exchange.number*10000>this.user.userglod2){
              this.$toast.fail('您的汪汪粮不足');
            }else{
              //修改用户的代币数量
              this.exchange.id = this.one.id;
              axios.post("http://localhost:9999/api-user/user/exchangeGlod",this.exchange).then(res=>{
                this.$toast.success("兑换完成")
                this.findOneUser();
                this.exchange.number = null;
              })
            }
          }
      },
      findOneUser(){
        axios.post("http://localhost:9999/api-user/user/findOneUser?id="+this.one.id).then(res=>{
          this.user = res.data;
        })
      },
      onBack(){
        this.$router.go(-1);
      }
    },
    created(){
      this.one = JSON.parse(localStorage.getItem("user"))

      if (this.one!=null){
        this.show = 1;
        this.findOneUser();
      }else{
        this.show = 2;
      }
    }
  }
</script>


<style scoped>

</style>
